package bm.com.ai.server.controller;

import bm.com.ai.server.dto.MessageRequest;
import bm.com.ai.server.dto.MessageResponse;
import bm.com.ai.server.rag.service.RagService;
import bm.com.ai.server.service.AIService;
import bm.com.ai.server.service.impl.AIServiceImpl;
import bm.com.framework.common.config.EnumRoute;
import dev.langchain4j.data.segment.TextSegment;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/common" +EnumRoute.AIRoute.Base)
public class ChatController {


    @Resource
    AIService aiService;

    @Resource
    AIServiceImpl aiServiceImpl;

    @Resource
    RagService ragService;

    @PostMapping(EnumRoute.AIRoute.Chat.CHAT)
    @Operation(summary = "与AI模型对话", description = "发送消息请求到AI模型并获取响应，支持多模态和RAG")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "成功获取响应",
                    content = @Content(schema = @Schema(implementation = MessageResponse.class))),
            @ApiResponse(responseCode = "400", description = "无效的请求参数")
    })
    public ResponseEntity<MessageResponse> chat(@RequestBody MessageRequest request) {
        MessageResponse response = aiService.processMessage(request);
        System.out.println("response : " + response);
        return ResponseEntity.ok(response);
    }

    @PostMapping(EnumRoute.AIRoute.Chat.RAG_CHAT)
    @Operation(summary = "添加文档到RAG系统", description = "向向量数据库添加文档，用于RAG检索")
    public ResponseEntity<Void> addDocumentsToRag(
            @RequestBody List<Map<String, String>> documents) {

        List<TextSegment> segments = documents.stream()
                .map(doc -> TextSegment.from(
                        doc.get("content"),
                        (dev.langchain4j.data.document.Metadata) Map.of(
                                "id", doc.getOrDefault("id", ""),
                                "source", doc.getOrDefault("source", "unknown"),
                                "title", doc.getOrDefault("title", "")
                        )
                ))
                .toList();

        ragService.addDocuments(segments);
        return ResponseEntity.ok().build();
    }
}
